(uiop:define-package #:reblocks/cached-dependencies-mixin
  (:use #:cl)
  (:import-from #:reblocks/dependencies
                #:get-dependencies)
  (:export #:cached-dependencies-mixin
           #:cached-dependencies
           #:cache-dependencies-p))
(in-package #:reblocks/cached-dependencies-mixin)


(defclass cached-dependencies-mixin ()
  ((dependencies :initform nil
                 :accessor cached-dependencies
                 :documentation "A list of cached dependencies.")
   (cache-dependencies :initform t
                       :initarg :cache-dependencies
                       :accessor cache-dependencies-p
                       :documentation "Boolean flag. When T then result of GET-DEPENDENCIES generic-function will be cached.
                                       By default is True, but you might turn it off while debugging the application."))
  (:documentation "If your widget might return a slightly different code from it's GET-DEPENDENCIES generic-function method,
                   these dependencies will be consided different and every-time loaded into the page.

                   Sometimes this happens with JS, generated by Parenscript, because it uses GENSYM in the
                   LET form. But actually code is the same and there is no need to load it again when
                   the widget is updated."))


(defmethod get-dependencies :around ((widget cached-dependencies-mixin))
  (cond
    ((cache-dependencies-p widget)
     (or (cached-dependencies widget)
         (setf (cached-dependencies widget)
               (call-next-method))))
    (t
     (call-next-method))))
